from custom_logger import PrefixDateLogger
from email_send import SendEmail
from monitor_dau_dnu_passive import DauDnuMonitor

logger = PrefixDateLogger("send_dau_dnu_alert")

# 执行脚本
if __name__ == "__main__":
    monitor = DauDnuMonitor()
    email = SendEmail()
    
    try:
        # 获取并分析数据
        logger.info("开始查询和分析DAU/DNU数据")
        df = monitor.get_dau_dnu_data()
        result = monitor.analyze_data(df)
        
        if not result:
            logger.info("没有数据或数据不足，程序退出")
        else:
            alerts, comparison_data, yesterday_date = result
            
            if alerts:
                # 发现告警，发送邮件
                logger.info(f"发现 {len(alerts)} 个告警指标，准备发送邮件")
                
                # 生成告警内容
                alert_content = monitor.generate_alert_content(alerts)
                
                # 生成数据表格
                table_html = monitor.generate_report_table(comparison_data)
                
                # 构建邮件正文
                body = f"""
                <h2>被动活跃DAU/DNU 数据异常告警</h2>
                <p>检测到以下指标昨天数据相比前三天平均值变化超过20%（上升或下降）：</p>
                {alert_content}
                
                <h3>部分User ID数据对比（前10个）：</h3>
                {table_html}
                
                <hr>
                <p style="color: #666; font-size: 12px;">
                    监控规则：昨天数据相比前3天平均值变化超过20%则告警（仅监控DAU和DNU）<br>
                    监控时间：{yesterday_date.strftime('%Y-%m-%d')}<br>
                    告警数量：{len(alerts)} 个指标<br>
                    已排除user_id=-1的数据<br>
                    此邮件由自动监控系统发送
                </p>
                """
                
                title = f"被动活跃DAU/DNU数据监控 - {yesterday_date.strftime('%Y-%m-%d')}"
                if len(alerts) > 0:
                    title = f"⚠️ 【告警】被动活跃DAU/DNU数据异常 - {yesterday_date.strftime('%Y-%m-%d')}"
                
                # 发送邮件（不带附件）
                try:
                    msg = email.send_email_with_screenshot(title, body, None)
                    logger.info("告警邮件发送成功")
                except Exception as e:
                    # 如果send_email_with_screenshot需要附件，使用纯文本发送
                    logger.warning(f"发送带附件邮件失败: {str(e)}，尝试发送纯文本邮件")
                    import smtplib
                    from email.mime.text import MIMEText
                    from email.mime.multipart import MIMEMultipart
                    
                    msg = MIMEMultipart()
                    msg["Subject"] = title
                    msg['From'] = email.email_config['sender']
                    msg['To'] = ','.join(email.email_config['receivers'])
                    msg.attach(MIMEText(body, "html", "utf-8"))
                    
                    with smtplib.SMTP_SSL(email.email_config['smtp_server'], email.email_config['smtp_port']) as server:
                        server.login(email.email_config['sender'], email.email_config['password'])
                        server.send_message(msg)
                    logger.info("纯文本告警邮件发送成功")
            else:
                logger.info("所有指标正常，未发现异常（DAU/DNU变化未超过20%），无需发送告警邮件")
    
    except Exception as e:
        logger.error(f"程序执行失败: {str(e)}", exc_info=True)
    finally:
        monitor.close()
        logger.info("程序执行完成")
